package com.hai.comtroller;

import com.alibaba.fastjson.JSON;
import com.hai.bean.User;
import org.apache.log4j.Logger;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by 黄海 on 2017/2/7.
 */
@RestController
public class CommonController {
    Logger log = Logger.getLogger(CommonController.class);

    /**
     * 返回一段字符串
     *
     * @return
     */
    @RequestMapping(value = "getCommonText", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getAText() {
        return "this is a common text for return  ";
    }

    /**
     * 返回一个User
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "getUser", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public User getUser(String username, String password, HttpServletRequest request) {
        System.out.println("getUser with name=" + username + ",pwd=" + password + ",method=" + request.getMethod());
        return new User(username, password);
    }

    @RequestMapping(value = "getUserReturnNull", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public User getUserReturnNull() {
        return null;
    }

    @RequestMapping(value = "getUserNull", method = RequestMethod.GET)
    @ResponseBody
    public String getUserNull() {
        return JSON.toJSONString(null);
    }

    /**
     * 返回一个UserList
     *
     * @return
     */
    @RequestMapping(value = "getUserList", method = RequestMethod.GET)
    @ResponseBody
    public String getUserList() {
        System.out.println("getUserList");
        List<User> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            list.add(new User("name" + i, "password" + i));
        }
        return JSON.toJSONString(list);
    }

    /**
     * 返回一个getUserListNull
     *
     * @return
     */
    @RequestMapping(value = "getUserListNull", method = RequestMethod.GET)
    @ResponseBody
    public String getUserListNull() {
        System.out.println("getUserList");
        List<User> list = new ArrayList<>();
        return JSON.toJSONString(list);
    }

    @RequestMapping(value = "postUser", method = RequestMethod.POST)
    @ResponseBody
    public User postUser(String username, String password) {
        log.debug(username + "," + password);
        return new User(username, password);
    }
}
